<?php
/**
 * Custom DjTpl tags for DbCollection
 *
 * @link http://webappkit.net
 * @package webappkit
 * @subpackage db
 * @author J.Ducastel <nospam0@ducastel.name>
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 */

/**
 * {% dbcollection collection page %} tag
 * sets context variables within block
 * dbcollection.pages = array(1,2,,n)
 * dbcollection.items = collection->getPage()
 * dbcollection.count = int
 */
class DjTplTagNode_DbCollection extends DjTplTagNode {

    /**
    * builds itself from tokens
    * @param djtplToken &$selfToken
    * @param array &$nextTokens djangoTplToken
    * @access public
    * @return bool
    */
    function buildFromTokens(&$selfToken, &$nextTokens) {
        // $this->token=&$selfToken;
        $def = explode(' ',$selfToken->tagdef); // print_r($def);
        // setting collection path
        $this->source = $def[0];
        if (isset($def[1]))
            $this->page = $def[1];
        // print_r($this);
        $this->buildChildNodesFromTokens($nextTokens);
        return true;
    }/**/

    /**
    * is the node atomic (has no children)
    * @access public
    * @return bool
    */
    function isAtomic() {
        return false;
    }/**/

    /**
    * renders as string
    * @param djangoTplContext $context
    * @access public
    * @return string
    */
    function render(&$context) {
        // getting collection
        $collection = $context->getPath($this->source); //print_r($collection);
        // setting aliases
        // setting empty array to avoid a bug when main container is an object
        $context->setPath('dbcollection',array());
        // total items count
        $context->setPath('dbcollection.count', $collection->count());
        // print_r($context); exit;
        // pagination, or all items

        if ($this->page) {
            $page = intval($context->getPath($this->page)); //print_r($page);
            // pages count, page index
            $context->setPath('dbcollection.pages', range(1,$collection->countPages()));
            $context->setPath('dbcollection.pageindex',$page);
            $context->setPath('dbcollection.items', $collection->getPage($page));
        } else {
            // all items
            $context->setPath('dbcollection.items', $collection->getList());
        }

        // echo $collection->count();
        return $this->renderChildNodes($context);
    }/**/

    /**
     * @var string collection path
     * @access protected
     */
    var $source;

    var $tagname = 'dbcollection';

    /**
     * @var string page index expression
     */
    var $page;
}

/**
 * pages browser
 */